import json
from SmartHouseServer_new.GLOBALVAR import mqtt_client
from SmartHouseServer_new.GLOBALVAR import massage_queue
import threading


# 连接成功回调
def on_connect(client, userdata, flags, rc):
    print('Connected with result code ' + str(rc))
    # 订阅主题
    client.subscribe('S_send')  # 北收南发
    client.subscribe('N_send')  # 南收北发


# 消息接收回调
def on_message(client, userdata, msg):
    msgs = (msg.topic + " " + str(msg.payload))


# 发送信息
class MQTTAPP(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(sel):
        mqtt_client.on_connect = on_connect
        mqtt_client.on_message = on_message
        # 建立连接
        mqtt_client.connect('139.159.235.171', 1883, 60)
        while True:
            payload_to_send = massage_queue.get(block=True)
            if payload_to_send is not None:
                mqtt_client.publish('N_send', payload=payload_to_send["payload_to_send"], qos=0)

        mqtt_client.loop_forever()


def run_mqtt():
    mqtt_app = MQTTAPP()  # 添加一个线程
    mqtt_app.start()  # 启动线程
    print('threading MQTT app start')


if __name__ == "__main__":
    run_mqtt()
